﻿using Microsoft.EntityFrameworkCore;
using SovaDataService.SoModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SovaDataService.SoDataServices
{
    public class CommentDataService
    {
        /**
         * Retrieves all the comments.
         */
        public IEnumerable<Comment> GetAll()
        {
            using (var db = new DbContext())
            {
                IQueryable<Comment> comments = db.Comments
                    .Include(c => c.Author)
                    .OrderBy(c => c.Id);
                return comments.ToList();
            }
        }

        /**
         * Retrieves one comment by given comment id.
         */
        public Comment GetOne(int id)
        {
            using (var db = new DbContext())
            {
                IQueryable<Comment> comment = db.Comments
                    .Where(c => c.Id == id);
                return comment.SingleOrDefault();
            }
        }

        /**
         * Retrieves all comments for a given question.
         */
        public IEnumerable<Comment>  GetCommentsForQuestion(int questionId)
        {
            using (var db = new DbContext())
            {
                IQueryable<Comment> comments = db.Comments
                    .Where(c => c.QuestionId == questionId)
                    .Include(c => c.Question)
                    .OrderBy(c => c.Id);

                return comments.ToList();

            }

        }
        
        /**
         * Retrieves all comments for a given answer.
         */
        public IEnumerable<Comment> GetCommentsForAnswer(int answerId)
        {
            using (var db = new DbContext())
            {
                IQueryable<Comment> comments = db.Comments
                    .Where(c => c.AnswerId == answerId)
                    .Include(c => c.Answer)
                    .OrderBy(c => c.Id);
                
                return comments.ToList();
            }
        }
        /**
         * Retrieves all comments for a given author.
         */
        public IEnumerable<Comment> GetCommentsForAuthor(int authorId)
        {
            using (var db = new DbContext())
            {
                IQueryable<Comment> comments = db.Comments
                    .Where(c => c.AuthorId == authorId)
                    .OrderBy(c => c.Id);

                return comments.ToList();
            }
        }

        /**
         * Retrieves the total without having to fetch all the comments from db.
         */
        public int GetCount()
        {
            using (var db = new DbContext())
            {
                return db.Comments.Count();
            }
        }
    }
}
